package com.xk.sport.backend.web.controller;

import com.google.common.base.Strings;
import com.xk.sport.backend.common.constant.Constants;
import com.xk.sport.backend.common.constant.ResultStatus;
import com.xk.sport.backend.common.entity.Result;
import com.xk.sport.backend.common.util.CookieUtil;
import com.xk.sport.backend.common.util.DesUtil;
import com.xk.sport.backend.dao.model.Admin;
import com.xk.sport.backend.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping(value = "/login")
public class LoginController {

    @Autowired
    private AdminService adminService;

    @RequestMapping("/login")
    @ResponseBody
    public Result login(HttpServletRequest request, HttpServletResponse response, String name, String password) {
        if (Strings.isNullOrEmpty(name) || Strings.isNullOrEmpty(password)) {
            return new Result(ResultStatus.normal_error.getStatus(), "参数错误");
        }
        Admin admin = adminService.findAdminByNameAndPassword(name, password);
        if (admin == null) {
            return new Result(ResultStatus.normal_error.getStatus(), "帐号不存在或密码错误");
        }
        long adminId = admin.getId();
        long now = System.currentTimeMillis();
        String key = adminId + "_" + now;
        try {
            key = DesUtil.encrypt(key, DesUtil.key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        CookieUtil.set(response, Constants.ADMIN_CACHE_KEY, key, 60 * 60);
        request.getSession().setAttribute(Constants.ADMIN_CACHE_KEY, key);

        Map<String, Object> data = new HashMap<>();
        data.put("nickname", admin.getNickname());
        data.put("name", admin.getName());
        data.put("role", admin.getRole());

        return new Result(ResultStatus.success.getStatus(), "", data);
    }

    @RequestMapping("/logout")
    @ResponseBody
    public Result logout(HttpServletRequest request, HttpServletResponse response) {
        String key = (String) request.getAttribute(Constants.KEY_REQUEST_KEY);
        CookieUtil.set(response, Constants.ADMIN_CACHE_KEY, "", 60 * 60);
        request.getSession().removeAttribute(Constants.ADMIN_CACHE_KEY);
        return new Result(ResultStatus.success.getStatus(), "");
    }

    @RequestMapping("/check")
    @ResponseBody
    public Result check() {
        return new Result(ResultStatus.success.getStatus(), "");
    }
}
